package com.learning.spring.cloud.alibaba.sentinel.order.web.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.learning.spring.cloud.alibaba.sentinel.order.web.mapper.OrderMapper;
import com.learning.spring.cloud.alibaba.sentinel.order.web.model.Order;
import com.learning.spring.cloud.alibaba.sentinel.order.web.rule.ResourceName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName: UserServiceImpl
 * Description:
 * Date: 2021/7/25 23:00 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;


    @Override
    public int insert(Order record) {
        return orderMapper.insert(record);
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return orderMapper.deleteByPrimaryKey(id);
    }


    @Override
    @Transactional(readOnly = true)
    @SentinelResource(value = ResourceName.ORDER_GET, blockHandler = "selectByPrimaryKeyBlockException", fallback = "selectByPrimaryKeyFallback")
    public Order selectByPrimaryKey(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Order> queryByUserId(Long userId) {
        return orderMapper.queryByUserId(userId);
    }


    /**
     * 1. 默认报错：Blocked by Sentinel (flow limiting)
     * Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
     *
     * @param id
     * @param throwable
     * @return
     */
    public Order selectByPrimaryKeyFallback(Long id, Throwable throwable) {
        Order order = new Order();
        order.setId(id);
        order.setName("电动牙刷");
        order.setUserId(-1L);
        return order;
    }

    public Order selectByPrimaryKeyBlockException(Long id, BlockException exception) {
        Order order = new Order();
        order.setId(id);
        order.setName("电动牙刷-BlockException");
        order.setUserId(-1L);
        return order;
    }

}
